import { AnimatePresence, m } from "framer-motion";
import * as RadixTooltip from "@radix-ui/react-tooltip";
import {
  forwardRef,
  isValidElement,
  PropsWithChildren,
  ReactNode,
  useState,
} from "react";
import { clsxm } from "../helpers";

type TooltipProps = PropsWithChildren<{
  content: ReactNode;
  delay?: number;
  className?: string;
  placement?: RadixTooltip.TooltipContentProps["side"];
  align?: RadixTooltip.TooltipContentProps["align"];
  placementOffset?: number;
  contentClassName?: string;
}>;

export const Tooltip = forwardRef<any, TooltipProps>(
  function Tooltip(props, ref) {
    const {
      children,
      content,
      delay = 300,
      className,
      placement,
      align,
      placementOffset,
      contentClassName,
      ...rest
    } = props;
    const [open, setOpen] = useState(false);
    return (
      <RadixTooltip.Provider delayDuration={delay}>
        <RadixTooltip.Root open={open} onOpenChange={setOpen}>
          <RadixTooltip.Trigger
            className={className}
            asChild={isValidElement(children)}
            ref={ref}
            {...rest}
          >
            {children}
          </RadixTooltip.Trigger>
          <AnimatePresence>
            {open && (
              <RadixTooltip.Portal forceMount>
                <RadixTooltip.Content
                  side={placement}
                  align={align}
                  sideOffset={placementOffset}
                  asChild
                >
                  <m.div
                    className={clsxm(
                      "relative z-[9999] min-w-max rounded-sm bg-white px-2 py-1 text-sm shadow-[0_9px_28px_8px_rgba(0,0,0,0.1)]",
                      contentClassName,
                    )}
                    initial={{ opacity: 0, scale: 0.9 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.9 }}
                  >
                    {content}
                  </m.div>
                </RadixTooltip.Content>
              </RadixTooltip.Portal>
            )}
          </AnimatePresence>
        </RadixTooltip.Root>
      </RadixTooltip.Provider>
    );
  },
);
